package cn.wyl.system.service.impl;

import cn.wyl.system.domain.Role;
import cn.wyl.system.mapper.RoleMapper;
import cn.wyl.system.service.IRoleService;
import cn.wyl.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {
    @Autowired
    RoleMapper roleMapper;
    @Transactional
    @Override
    public void remove(Long id) {
        //删除中间表：t_role_permission
        roleMapper.removeRolePermissionByRoleId(id);
        //删除中间表：t_role_menu
        roleMapper.removeRoleMenuByRoleId(id);
        //删除中间表：t_employee_role
        roleMapper.removeEmployeeRole(id);
        //删除角色
        roleMapper.remove(id);
    }

    //批量删除重构
    @Transactional
    @Override
    public void patchDel(List<Long> ids) {
        for(Long id:ids){
            remove(id);
        }
    }


    @Transactional
    @Override
    public void save(Role role){
        //保存角色信息
        roleMapper.save(role);
        //操作相关信息：中间表信息
        initRelationTable(role);
    }

    @Transactional
    @Override
    public void update(Role role) {
        roleMapper.update(role);
        //删除中间表信息：t_role_permission
        roleMapper.removeRolePermissionByRoleId(role.getId());
        //删除中间表信息：t_role_menu
        roleMapper.removeRoleMenuByRoleId(role.getId());
        initRelationTable(role);
    }

    /**
     * 添加中间表：t_role_permission ,t_role_menu
     * @param role
     */
    private void initRelationTable(Role role) {
       if (role.getPermissions().size()>0){
           roleMapper.saveRolePermissons(role.getId(),role.getPermissions());
       }
        if (role.getMenus().size()>0) {
            roleMapper.saveRoleMenus(role.getId(), role.getMenus());
        }
    }



}
